<?php
namespace app\controller;

use app\BaseController;

use think\facade\Db;
use think\Request;
use think\captcha\facade\Captcha;
use think\cache\driver\Redis;
use think\facade\Cache;

/**
* 充提币 资金记录
* 20210720
*/
class Coin extends BaseController
{
	protected $userInfo;
	protected $request;
	public function __construct(Request $request){
        $this->request = $request;
        $this->token = $this->request->header('token');
        $requests = new Request_type();
        if($this->token){
            $this->userInfo = $requests->getUserInfo($this->token);
        }
        
	}

	/**
	 * 充提币配置
	 * @return json_encode([type] [description]
	 */
	public function config(){
		$config = Db::table("t_coin_config")->where("coin_name","USDT")->find();

		return json_encode(array("code"=>200,"msg"=>'成功','data'=>$config));
	}

	/**
	 * 充币地址
	 * @return json_encode([type] [description]
	 */
	public function address(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
        $address = Db::table("t_trc_address")->where("user_id",$this->userInfo['id'])->value("address");
        if(!$address){
        	return json_encode(array("code"=>'111',"msg"=>'帳戶异常，請聯系客服'));
        }

        return json_encode(array("code"=>200,"msg"=>'成功','data'=>$address));
	}

	/**
	 * 提币操作
	 * @return json_encode([type] [description]
	 */
	public function carry(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
		$data = $this->request->param();
		if(!$data['address']){
			return json_encode(array("code"=>'113',"msg"=>'提幣地址不能為空'));
		}
		if(!$data['money']){
			return json_encode(array("code"=>'114',"msg"=>'提幣金額不能為空'));
		}
		if(Db::table("t_user_send_ban")->where("user_id",$this->userInfo['id'])->find()){
			return json_encode(array("code"=>'112',"msg"=>'提幣帳戶异常，請聯系客服'));
		}
		$google = Db::table("t_google_secret")->where("user_id",$this->userInfo['id'])->where("status",1)->find();
		if(!$google){
			return json_encode(array("code"=>'116',"msg"=>'提幣前請先綁定穀歌驗證碼'));
		}else{
			$google1=new GoogleAuthenticator();
	        //$google_secret 存入的谷歌秘钥  ，$code 谷歌动态验证码
	        $checkResult = $google1->verifyCode($google['secret'], $data['code'], 4);
	        if (!$checkResult){
	        	return json_encode(array("code"=>'117',"msg"=>'穀歌驗證碼錯誤'));
	        }
		}
		$balance = Db::table("t_user_coin")->where("user_id",$this->userInfo['id'])->where("coin_name",'USDT')->value('available_balance');
		$config = Db::table("t_coin_config")->where("coin_name","USDT")->find();		
		if($data['money'] > $config['transfer_max_amount'] || $data['money'] < $config['transfer_min_amount'] || !is_numeric($data['money'])){
			return json_encode(array("code"=>'115',"msg"=>'提幣金額超過限制'));
		}
		if($config['transfer_fee_select'] == 1){
			$fee = $config['transfer_fee_static'];
		}else{
			$fee = $data['money']*$config['transfer_fee_rate'];
		}
		if($data['money']  > $balance){
			return json_encode(array("code"=>'116',"msg"=>'餘額不足'));
		}
		$user_id = Db::table("t_trc_address")->where("address",$data['address'])->value('user_id');
		$dataArray =array(
			"user_id"=>$this->userInfo['id'],
			'address'=>$data['address'],
			'coin_name'=>'USDT',
			'amount'=>$data['money'],
			'fee'=>$fee,
			'send_time'=>date("Y-m-d H:i:s"),
			'last_time'=>date("Y-m-d H:i:s"),
			'token'=>'TRC20'
		);
		$bill_1=array(
			'user_id'=>$this->userInfo['id'],
			'coin_name'=>'USDT',
			'sub_type'=>0,
			'reason'=>'Withdraw',
			'change_amount'=>-($data['money']+$fee),
			'comment'=>'用户提现',
			'last_time'=>date("Y-m-d H:i:s")
		);
		Db::startTrans();
		try {
			if(!$user_id){
				Db::table("t_user_coin")->where("user_id",$this->userInfo['id'])->inc('freeze_balance',$data['money'])->update();
				Db::table('t_user_coin')->where("user_id",$this->userInfo['id'])->dec('available_balance',$data['money'])->update();
				$dataArray['status'] = 0;
				$dataArray['second_status'] = 0;
				$dataArray['txid'] = md5(time());
				$bill_2=array(
					'user_id'=>$this->userInfo['id'],
					'coin_name'=>'USDT',
					'sub_type'=>1,
					'reason'=>'Withdraw',
					'change_amount'=>$data['money']+$fee,
					'comment'=>'用戶提現凍結',
					'last_time'=>date("Y-m-d H:i:s")
				);
			}else{
			    if($user_id == $this->userInfo['id']){
			        Db::rollback();

		            return json_encode(array("code"=>'125',"msg"=>'自己不能給自己轉帳'));
			    }
				Db::table("t_user_coin")->where("user_id",$user_id)->inc('available_balance',$data['money'])->update();
				Db::table('t_user_coin')->where("user_id",$this->userInfo['id'])->dec('available_balance',$data['money']+$fee)->update();
				$dataArray['status'] = 1;
				$dataArray['second_status'] = 1;
				$dataArray['received_user_id'] = $user_id;
				$dataArray['txid'] = 'inner-'.md5(time());
				$bill_2=array(
					'user_id'=>$user_id,
					'coin_name'=>'USDT',
					'sub_type'=>0,
					'reason'=>'Transfer',
					'change_amount'=>$data['money'],
					'comment'=>'用戶內部充值',
					'last_time'=>date("Y-m-d H:i:s")
				);
			}
			Db::table("t_send_coin")->save($dataArray);
			Db::table("t_user_bill")->insert($bill_1);
			Db::table("t_user_bill")->insert($bill_2);
			Db::commit();
			return json_encode(array("code"=>200,"msg"=>'成功'));
		}catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();

		    return json_encode(array("code"=>100,"msg"=>'失败','data'=>$e->getMessage()));
		}
	}

	/**
	 * 充值/提币详情
	 * @return json_encode([type] [description]
	 */
	public function record(){

	}

	/**
	 * 提币记录
	 * @return json_encode([type] [description]
	 */
	public function withdraw(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_send_coin")->where("user_id",$this->userInfo['id'])->where("coin_name","USDT")->page($page,$pageSize)->select()->toArray();
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
	
	/**
	 * 充值记录
	 * @return json_encode([type] [description]
	 */
	public function recharge(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_received_coin")->where("user_id",$this->userInfo['id'])->where("coin_name","USDT")->page($page,$pageSize)->select()->toArray();
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}

	/**
	 * 购买投资
	 * @return json_encode([type] [description]
	 */
	public function purchase(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	   // $list = Db::table("t_purchase_user")->alias("a")->join("t_purchase b","a.p_id = b.id")->field("sum(a.number) as number,a.last_time,b.price,b.status,b.coin_name,a.p_id")->where("a.user_id",$this->userInfo['id'])->group("a.p_id")->order("a.id desc")->page($page,$pageSize)->select()->toArray();
	    $list = Db::table("t_purchase_user")->alias("a")->join("t_purchase b","a.p_id = b.id")->field("b.price,b.status,b.coin_name,a.*")->where("a.user_id",$this->userInfo['id'])->order("a.id desc")->page($page,$pageSize)->select()->toArray();
	    if($list){
	        foreach ($list as $k=>$v){
	            $list[$k]['shij'] = Db::table("t_purchase_personal")->where("id",$v['p_id'])->where("user_id",$this->userInfo['id'])->value("ctime");
	            if(!$list[$k]['shij']){
	                $list[$k]['shij'] = '待釋放';
	            }
	            $haoma = Db::table("t_purchase_user_details".$v['p_id'])->where("p_u_id",$v['id'])->order("id desc")->limit(20)->column("id");
	            $list[$k]['haoma'] = implode(",",$haoma);
	        }
	    }
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}

	/**
	 * 奖励记录
	 * 个人参与活动奖励记录
	 * @return json_encode([type] [description]
	 */
	public function reward(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_purchase_personal")->alias("a")->join("t_purchase b","a.p_id = b.id")->field("a.*,b.price,b.status,b.coin_name")->where("a.user_id",$this->userInfo['id'])->order("a.id desc")->page($page,$pageSize)->select()->toArray();
	    
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}

	/**
	 * 推荐奖励记录
	 * @return json_encode([type] [description]
	 */
	public function recommend(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_purchase_recommend")->alias("a")->join("t_purchase b","a.p_id = b.id")->field("a.*,b.price,b.status,b.coin_name")->where("a.user_id",$this->userInfo['id'])->order("a.id desc")->page($page,$pageSize)->select()->toArray();
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
	
	
	public function big_reward(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_purchase_big")->where("user_id",$this->userInfo['id'])->order("id desc")->page($page,$pageSize)->select()->toArray();
	    if($list){
	        foreach ($list as $k=>$v){
	            $list[$k]['coin_name'] = 'USDT';
	        }
	    }
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
	
	public function big(){
// 	    $data = $this->request->param();
// 		$page = $data['page']?$data['page']:1;
// 	    $pageSize = $data['pageSize']?$data['pageSize']:10;
        $amount = Db::table("t_purchase_retained")->order("id desc")->value("money");
	    $list['amount'] = Db::table("t_purchase_big_reward")->where("status",0)->sum("amount");
	    $list['p_id'] = Db::table("t_purchase_big_reward")->where("status",0)->max("p_id");
	    $list['amount'] = $list['amount']+$amount;
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
}